package com.campus.secondhand.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;

import com.campus.secondhand.security.JwtAuthenticationFilter;
import com.campus.secondhand.security.JwtAuthenticationEntryPoint;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
@Slf4j
public class WebSecurityConfig {

    private final JwtAuthenticationEntryPoint unauthorizedHandler;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 禁用CSRF
                .csrf(AbstractHttpConfigurer::disable)
                // 禁用HTTP Basic认证
                .httpBasic(AbstractHttpConfigurer::disable)
                // 禁用form登录
                .formLogin(AbstractHttpConfigurer::disable)
                // 禁用登出
                .logout(AbstractHttpConfigurer::disable)
                // 配置session管理为无状态
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置异常处理
                .exceptionHandling(exceptionHandling -> exceptionHandling
                        // 身份验证入口点
                        .authenticationEntryPoint(unauthorizedHandler))
                // 配置授权请求
                .authorizeHttpRequests(authorize -> authorize
                        // 开放认证相关接口
                        .requestMatchers("/auth/login", "/auth/register", "/auth/verify-code/**",
                                "/auth/forget-password", "/auth/refresh-token", "/auth/check-status",
                                "/user/login", "/user/register", "/user/send-code", "/user/reset-password",
                                "/user/check-status")
                        .permitAll()
                        // 开放学校相关接口
                        .requestMatchers("/schools/**").permitAll()
                        // 开放商品查看接口
                        .requestMatchers("/products", "/products/{id}").permitAll()
                        .requestMatchers("/products/{id}/view").permitAll()
                        .requestMatchers("/products/categories/**").permitAll()
                        // 开放求购信息查看接口 (GET)
                        .requestMatchers(org.springframework.http.HttpMethod.GET, "/requests", "/requests/{id}")
                        .permitAll()
                        .requestMatchers(org.springframework.http.HttpMethod.GET, "/requests/{id}/view").permitAll()
                        // 开放文件访问接口
                        .requestMatchers("/uploads/**").permitAll()
                        // 开放静态资源
                        .requestMatchers("/", "/index.html", "/static/**", "/css/**", "/js/**",
                                "/images/**", "/fonts/**", "/favicon.ico")
                        .permitAll()
                        // 开放Swagger相关接口
                        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
                        // 开放登录、注册页面
                        .requestMatchers("/login", "/register", "/forgot-password").permitAll()
                        // 其余接口需要认证
                        .anyRequest().authenticated())
                // 添加JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                // 允许CORS
                .cors(cors -> cors.configurationSource(corsConfigurationSource()));

        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        log.info("配置CORS...");
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(List.of("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With", "Accept"));
        configuration.setExposedHeaders(Arrays.asList("Authorization"));
        configuration.setAllowCredentials(false);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        log.info("CORS配置完成");
        return source;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }
}